#include "CollapsibleWidget.h"
#include "Widgets/Mouse/MouseWidget.h"
#include "Widgets/Positioners/VerticalPositionerWidget.h"

RCollapsibleWidget::RCollapsibleWidget()
{
    Title=NewWidget<RWidget>(this);
    Title->Height=20;
    Title->Anchor.HorizontalFill(this);

    Content=NewWidget<RVerticalPositionerWidget>(this);
    Content->Anchor.HorizontalFill(this);
    Content->Anchor.TopReference=Title;
    Content->Anchor.TopReferenceEdge=EVerticalWidgetEdge::Bottom;

    auto Mouse = NewWidget<RMouseWidget>(Title);
    Mouse->Anchor.Fill(Title);
    Mouse->OnClicked.BindLambda([this](const SMouseButtonEvent&)->bool
    {
        if(bIsCollapsed)
        {
            Expand();
        }
        else
        {
            Collapse();
        }

        return true;
    });
}

RWidgetPtr RCollapsibleWidget::GetTitle()
{
    return Title;
}

RVerticalPositionerWidgetPtr RCollapsibleWidget::GetContent()
{
    return Content;
}

void RCollapsibleWidget::Expand()
{
    bIsCollapsed=false;

    if(OnExpand.IsBound())
    {
        OnExpand.Execute();
    }
}

void RCollapsibleWidget::Collapse()
{
    bIsCollapsed=true;

    if(OnCollapse.IsBound())
    {
        OnCollapse.Execute();
    }
}

float RCollapsibleWidget::CalculateContentHeight()
{
    return TotalHeight;
}

void RCollapsibleWidget::CalculateChildrenPresentPositionAndSize()
{
    ArrangeContent();
}

void RCollapsibleWidget::PaintSubWidgets( uint16_t &InZOrder)
{
    Title->Paint(InZOrder);

    if(!bIsCollapsed)
    {
        Content->Paint(InZOrder);
    }

}

void RCollapsibleWidget::ArrangeContent()
{
    Title->CalculatePresentPositionAndSize();

    if(!bIsCollapsed)
    {
        Content->CalculatePresentPositionAndSize();
    }

    TotalHeight=Title->PresentSize.Y;
    if(!bIsCollapsed)
    {
        TotalHeight+=Content->PresentSize.Y;
    }
}
